package tcln.gxtx.client.utils.store;

import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.TreeModel;
import com.extjs.gxt.ui.client.store.Record;
import com.extjs.gxt.ui.client.store.TreeStore;

/**
 * An extension of {@link TreeStore} to better control on Store's behavior.
 * 
 * @param <M>
 *            Model data type.
 * @author Truong Chau Lien Ngoc (lienngoc@gmail.com)
 */
public class ExtendedTreeStore<M extends ModelData> extends TreeStore<M> {

    /**
     * A flag indicating if {@link #afterEdit(Record)} should be disabled or not.
     */
    boolean afterEditDisabled;

    /**
     * A flag indicating if this store should NOT apply any filter on inserting data into this store. This means, method
     * {@link #getChildCount(ModelData)} should return directly
     * {@link com.extjs.gxt.ui.client.data.BaseTreeModel#getChildCount()} in this case.
     */
    boolean filteringIgnored;

    /**
     * Sets new value for afterEditDisabled.
     * 
     * @param afterEditDisabled
     *            the afterEditDisabled to set.
     */
    public void setAfterEditDisabled(boolean afterEditDisabled) {
        this.afterEditDisabled = afterEditDisabled;
    }

    /**
     * Sets new value for filteringIgnored.
     * 
     * @param filteringIgnored
     *            the filteringIgnored to set.
     */
    public void setFilteringIgnored(boolean filteringIgnored) {
        this.filteringIgnored = filteringIgnored;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int getChildCount(M parent) {
        if (filteringIgnored) {
            if (parent == null) {
                return getChildCount();
            } else {
                TreeModel p = findWrapper(parent);
                if (p != null) {
                    return p.getChildCount();
                }
                return -1;
            }
        } else {
            return super.getChildCount(parent);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void afterEdit(Record record) {
        if (!afterEditDisabled) {
            super.afterEdit(record);
        }
    }
}
